'use strict';

import { usergamehistoryModel } from "../model/usergamehistory";
import { ServiceBase, Exceptions } from '../kalend';
import { usertokenService } from "./usertoken";
import { ObjectId } from "bson";
import { customer_accountService } from "./customer_account";
var moment = require("moment");

class UsergamehistoryService extends ServiceBase {
    constructor() {
        super(usergamehistoryModel)
    }
    async query(params: any) {
        const offset = params.page || 1;
        const limit = params.limit || 50;
        const token = params.token;
        if (!token) {
            throw Exceptions.notoken();
        }
        let userid = (await usertokenService.getToken(token)).userid;
        let data = await this.queryPagination(offset, limit, {
            filter: { userid: userid, win: true },
            select: 'createTime remarks status'
        });
        data.rows= data.rows.map((item) => {
            item.gametime = moment(item.createTime).format("YYYY-MM-DD HH:mm:ss");
            item.state = item.status ? '已领取' : '未领取';
            return item;
        });
        return data.rows;
    }
    async save(doc: any) {
        let token = doc.token;

        if (!token) {
            throw Exceptions.notoken();
        }
        let userid = (await usertokenService.getToken(token)).userid;
        if (userid) {
            doc.userid = userid;
            doc.joinDate = moment(new Date()).format('YYYY-MM-DD');
            console.log(doc.joinDate);
            // 验证本日是否还有抽奖次数
            let gethis = await this.querySingle({ userid: userid, joinDate: doc.joinDate });
            if (!gethis || gethis.count > 0) {
                let his = await this.create(doc);
                return {
                    id: his._id.toJSON(),
                    msg: '保存抽奖记录成功'
                };
            } else {
                return {
                    msg: '您本日已无抽奖次数'
                };
            }
        } else {
            return {
                msg: '保存抽奖记录失败'
            };
        }
    }

    async getgift(id: any) {
        let his = await this.exist({ _id: id, status: 0 });
        if (his) {
            let data = await this.update(id, { status: 1 });
            console.log('奖品领取成功');
            // 执行奖品逻辑
            if (data.conins > 0) {
                customer_accountService.addcoins(data.userid, data.conins);
            }
            return {
                conins: data.conins,
                msg: '奖品领取成功'
            };
        } else {
            console.log('----警告警告警告------抽奖活动：有人刷奖品！-------警告警告警告-------');
            throw Exceptions.known('奖品领取失败');
        }
    }
}

export const usergamehistoryService = new UsergamehistoryService();